package com.china08.yxyapi.api.manage.sch.platform.website;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.sws.SwsSchoolTemplet;
import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.db.sws.SwsSection.DisplayStyle;
import com.china08.yxyapi.entity.db.sws.SwsSetting;
import com.china08.yxyapi.entity.db.sws.SwsSetting.LogoStyle;
import com.china08.yxyapi.entity.db.sws.SwsSettingDomains;
import com.china08.yxyapi.entity.db.sws.SwsTempletModule;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.SwsModuleRepository;
import com.china08.yxyapi.repository.db.SwsSchoolTempletRepository;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.db.SwsSettingDomainsRepository;
import com.china08.yxyapi.repository.db.SwsSettingRepository;
import com.china08.yxyapi.repository.db.SwsTempletModuleRepository;

@CrossOrigin
@RestController
public class WebSiteInitController extends YxyApiBaseController {

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    SwsSettingRepository swsSettingRepository;

    @Autowired
    SwsSettingDomainsRepository swsSettingDomainsRepository;

    @Autowired
    SwsModuleRepository SwsModuleRepository;

    @Autowired
    SwsTempletModuleRepository swsTempletModuleRepository;

    @Autowired
    SwsSchoolTempletRepository swsSchoolTempletRepository;

    @Autowired
    SwsSectionRepository swsSectionRepository;

    Logger Logger = LoggerFactory.getLogger(WebSiteInitController.class);

    @RequestMapping(value = "/api_yw/manage/sch/platform/website/init", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) ReqModel reqModel) {
        RespModel respModel = new RespModel();
        String schoolId = getProfile(request, response).getSchoolId();
        Assert.isTrue(StringUtils.isNotBlank(schoolId), "未获取当前学校信息");

        // 默认模版id
        String defaultTempId = "templ002";
        // 默认主题id
        String defaultThemeId = "theme001";
        // 默认配色id
        String defaultColorId = "color001";

        // 获取学校配置信息

        // 基本信息
        List<SwsSetting> swsSettings = swsSettingRepository.findBySchoolIdAndSchoolIdNotNull(schoolId);
        Assert.isTrue(swsSettings.size() <= 1, "当前学校进行了多次配置");

        if (swsSettings.size() == 0) {
            Map<String, String> map = restTemplate.getForObject(yxyApiYxUrl + "/comm/school/" + schoolId, Map.class);

            String schoolNick = map.get("schoolNick");
            String address = map.get("address");
            String tel = map.get("tel");
            String faceImg = map.get("faceImg");
            // 补全图片路径
            if (StringUtils.isNotBlank(faceImg)) {
                faceImg = (faceImg.startsWith("http") || faceImg.startsWith("https")) ? faceImg : "https://yxcsp.91yunxiao.com/yxcsp/pull/" + faceImg;
            }
            // 截取字符串
            String intro = map.get("intro");
            String seo = map.get("intro");
            if (StringUtils.isNotBlank(intro) && intro.length() > 2000) {
                intro = intro.substring(0, 1996) + "...";
            }
            if (StringUtils.isNotBlank(seo) && seo.length() > 500) {
                seo = seo.substring(0, 495) + "...";
            }
            SwsSetting swsSetting = new SwsSetting();
            swsSetting.setSchoolId(schoolId);
            swsSetting.setSchoolName(schoolNick);
            swsSetting.setAddress(address);
            swsSetting.setDescription(intro);
            swsSetting.setTelephone(tel);
            swsSetting.setSchoolLogo(faceImg);
            swsSetting.setKeywords(schoolNick);
            swsSetting.setSeoDescription(seo);
            // 默认网站初始化信息，使用第二套模版，第一主题，第一配色
            swsSetting.setSkinTempl(defaultTempId);
            swsSetting.setSkinTheme(defaultThemeId);
            swsSetting.setSkinColor(defaultColorId);
            swsSetting.setLogoSetting(LogoStyle.BADGE_NAME);
            swsSettingRepository.save(swsSetting);
            Logger.error("初始化基本信息成功");
        }

        // 初始化网站域名
        List<SwsSettingDomains> swsSettingDomainsList = swsSettingDomainsRepository.findBySchoolId(schoolId);
        if (swsSettingDomainsList.size() == 0) {
            SwsSettingDomains settingDomains = new SwsSettingDomains();
            settingDomains.setId(UUID.randomUUID().toString().replace("-", ""));
            settingDomains.setSchoolId(schoolId);
            swsSettingDomainsRepository.save(settingDomains);
            Logger.error("初始化网站域名成功");
        }

        // 初始化模块
        List<SwsSchoolTemplet> swsSchoolTempletList = swsSchoolTempletRepository.findBySchoolId(schoolId);
        if (swsSchoolTempletList.size() == 0) {
            // 获取模版2的所有模块
            List<SwsTempletModule> templList = swsTempletModuleRepository.findByTemplateId(defaultTempId);
            for (SwsTempletModule swsTempletModule : templList) {
                Integer orderNum = templList.indexOf(swsTempletModule) + 1;
                SwsSchoolTemplet swsSchoolTemplet = new SwsSchoolTemplet();
                swsSchoolTemplet.setId(UUID.randomUUID().toString().replace("-", ""));
                swsSchoolTemplet.setSchoolId(schoolId);
                swsSchoolTemplet.setTemplateId(defaultTempId);
                swsSchoolTemplet.setOrderNum(orderNum);
                swsSchoolTemplet.setModuleId(swsTempletModule.getModuleId());
                swsSchoolTempletRepository.save(swsSchoolTemplet);
            }
            Logger.error("初始化模块成功");
        }

        // 栏目设置
        List<SwsSection> swsSectionList = swsSectionRepository.findBySchoolId(schoolId);
        if (swsSectionList.size() == 0) {
            String[] strings = { "学校概况", "新闻中心", "师资队伍", "招生信息", "课程中心", "班级动态" };
            int orderNum = 1;
            for (String string : strings) {
                SwsSection swsSection = new SwsSection();
                swsSection.setId(UUID.randomUUID().toString().replace("-", ""));
                swsSection.setSectionName(string);
                swsSection.setSchoolId(schoolId);
                swsSection.setPid("0");
                swsSection.setIsVisible(true);
                swsSection.setIsOutLink(false);
                swsSection.setIsAudit(false);
                swsSection.setDisplayStyle(DisplayStyle.TEXT_LIST);
                swsSection.setSectionType(0);
                swsSection.setOrderNum(orderNum);
                swsSectionRepository.save(swsSection);
                orderNum = orderNum + 1;
            }
            Logger.error("栏目设置成功");
        }
        return respModel;
    }

    protected static class ReqModel extends YxyApiPageReqModel {

    }

    protected static class RespModel extends YxyApiRespModel {
        // 初始化成功
        public boolean success = true;
    }
}
